package com.zhang.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.goods.entity.Category;
import com.zhang.goods.mapper.CategoryMapper;
import com.zhang.goods.service.ICategoryService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 分类表 服务实现类
 * </p>
 *
 * @author 创世神
 * @since 2023-08-28
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    List<Category> getTree(List<Category> all, List<Category> parents) {
        List<Category> list = parents.stream().map(pitem -> {
            List<Category> collect = all.stream().filter(citem -> citem.getParentId().equals(pitem.getId())).collect(Collectors.toList());
//           使用递归继续遍历设置
            List<Category> tree = getTree(all, collect);
            pitem.setChildren(tree);
            return pitem;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public List<Category> getTreeList() {
        List<Category> all = list();
//        删选出顶级分类
        List<Category> tree = all.stream().filter(item -> item.getParentId().equals(0L)).collect(Collectors.toList());
        return getTree(all, tree);
    }

    @Override
    public boolean delCategory(Long categoryId) {
        /*检查是否具有子节点*/
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", categoryId);
        Category one = getOne(wrapper, false);
        if (one == null) {
            boolean b = removeById(categoryId);
            return b;
        }
        return false;
    }

    @Override
    public List<Category> ListByParentId(Long parentId) {
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);
        List<Category> list = list(wrapper);
        return list;
    }

    @Override
    public List<Category> treeListByParentId(Long parentId) {
        /*由于这里并不是从一级分类获取，就不需要递归了，因为最多只有两级分类*/
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",parentId);
        List<Category> list = list(wrapper);
        list.stream().forEach(item->{
            List<Category> childrens = list(new QueryWrapper<Category>().eq("parent_id", item.getId()));
            if (childrens!=null || childrens.size()>0) {
                item.setChildren(childrens);
            }
        });
        return list;
    }

}
